package org.example.Servlet.vote;

import org.example.Dao.VoteDao;
import org.example.entity.Person;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/vote/save")
public class SaveVoteServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        int oid = Integer.parseInt(req.getParameter("oid"));
        int tid = Integer.parseInt(req.getParameter("tid"));
        //获取当前的用户id
        Person person = (Person) session.getAttribute("person");
        int pid = person.getPid();

        VoteDao voteDao = new VoteDao();
        int count = 0;
        try {
            count = voteDao.save(oid, pid, tid);
            System.out.println("save vote count ==> " + count);
            session.setAttribute("saveVoteMsg", "");
            resp.sendRedirect(req.getContextPath() + "/vote/show?tid=" + tid);
        } catch (Exception e) {
            System.out.println("save vote error ==> " + e.getMessage());
            session.setAttribute("saveVoteMsg", "投票失败");
            resp.sendRedirect(req.getContextPath() + "/vote/show?tid=" + tid);
        }
    }
}
